﻿using ConsolePro.Practice;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.AspNetCore.Http;
using System.Security.Cryptography;
using System.IO;

namespace ConsolePro
{
    class Program
    {
        public static string DES_Encrypt(string strEncrypt)
        {
            try
            {
                if (string.IsNullOrEmpty(strEncrypt)) return string.Empty;
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                des.Padding = PaddingMode.PKCS7;
                byte[] inputByteArray = Encoding.Default.GetBytes(strEncrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes("ZIM4x2lb");// 密匙
                des.IV = ASCIIEncoding.ASCII.GetBytes("ZIM4x2lb");// 初始化向量
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                var retB = BytesTohexString(ms.ToArray());
                return retB;
            }
            catch (Exception ex)
            {
                throw new Exception($"DES明文加密失败，失败原因：{ex.Message.ToString()}");
            }
        }

        /// <summary>
        /// 将字节流转化为16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private static string BytesTohexString(byte[] bytes)
        {
            if (bytes == null || bytes.Count() < 1) return string.Empty;

            var count = bytes.Count();
            var cache = new StringBuilder();
            //cache.Append("0x");
            for (int ii = 0; ii < count; ++ii)
            {
                var tempHex = Convert.ToString(bytes[ii], 16).ToUpper();
                cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex);
            }

            return cache.ToString();
        }


        public static string DES_Decrypt(string strDecrypt, string strKey= "ZIM4x2lb")
        {
            try
            {
                if (string.IsNullOrEmpty(strDecrypt)) return string.Empty;
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                des.Padding = PaddingMode.PKCS7;
                byte[] inputByteArray = HexStringToBytes(strDecrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes(strKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(strKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);  // 如果两次密匙不一样，这一步可能会引发异常
                cs.FlushFinalBlock();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw new Exception($"DES密文解密失败，失败原因：{ex.Message.ToString()}");
            }
        }

        /// <summary>
        /// 将16进制字符串转化为 字节流
        /// </summary>
        /// <param name="hexStr"></param>
        /// <returns></returns>
        private static byte[] HexStringToBytes(string hexStr)
        {
            if (string.IsNullOrEmpty(hexStr)) return new byte[0];

            if (hexStr.StartsWith("0x")) hexStr = hexStr.Remove(0, 2);

            var count = hexStr.Length;

            if (count % 2 == 1) throw new ArgumentException("Invalid length of bytes:" + count);

            var byteCount = count / 2;
            var result = new byte[byteCount];
            for (int ii = 0; ii < byteCount; ++ii)
            {
                var tempBytes = Byte.Parse(hexStr.Substring(2 * ii, 2), System.Globalization.NumberStyles.HexNumber);
                result[ii] = tempBytes;
            }

            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(DES_Decrypt("6158EB39B5DA00CB81531603C9A8AB847CCDBD7B39F3186E"));// 100
            Console.WriteLine(DES_Decrypt("B4D8900E47736EB8F1910EDB61FA3A777ADB99F466B80A08"));// 200
            // B08F4D4527C8BC5EE453B18490855B8DF518701FBC15E505


            /*int port = 9999;
            var ip = IPAddress.Any;
            var receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            receiveSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            var endPoint = new IPEndPoint(ip, port);
            receiveSocket.Bind(endPoint); //绑定IP地址和端口号
            receiveSocket.Listen(10);
            Console.WriteLine("开始监听Accpet\n");

            // 接收到得到对应客户端TCP连接 这里会阻塞
            Socket socket = receiveSocket.Accept();

            Console.WriteLine("Connection!");
            Console.ReadKey();
            var buffer = new byte[1024];
            socket.Receive(buffer);
            var reqHeader = Encoding.UTF8.GetString(buffer);
            Console.WriteLine($"接收到消息：\n" + reqHeader);

            // 回执
            var content = "<html><H1>Hello world!</H1></html>";
            var heads = Encoding.UTF8.GetBytes($"HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=UTF-8\r\nContent-Length:{content.Length}\r\n\r\n");  //应答头
            socket.Send(heads);  //发送头
            socket.Send(Encoding.UTF8.GetBytes(content));  //发送正文

            Console.WriteLine("press any key to close socket!");
            Console.ReadKey();
            socket.Close();
            Console.WriteLine("socket close!");

            Console.WriteLine("Main End!");
            Console.ReadKey();*/
        } 

    }
}
